package com.lgcns.android2;

import java.util.ArrayList;
import java.util.HashMap;

import com.lgcns.android2.ProfileListActivity.ProfileViewHolder;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.QuickContactBadge;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class MultiSendingSMS extends Activity{

    ListView teammultilist;
    Button selectcompletebtn;
    Button searchbtn;
    Spinner spinner;
    EditText searchtext;
    
    private String array_spinner[];
    
    String titleSelected;
    int positionSelected;
    
    HashMap<String, Object> map;
    
    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.multismslist);
        
        Toast.makeText(this, "SMS전송은 최대 20명까지 가능합니다.", Toast.LENGTH_SHORT).show();
        
        teammultilist = (ListView) findViewById(R.id.teammultilist);
        selectcompletebtn = (Button) findViewById(R.id.selectcompletebtn);
        searchbtn = (Button) findViewById(R.id.searchbtn);
        spinner = (Spinner) findViewById(R.id.spinner);
        searchtext = (EditText) findViewById(R.id.searchtext);
        
        map = new HashMap<String, Object>();
        
        array_spinner = new String[6];
        array_spinner[0] = "(모두)";
        array_spinner[1] = "차장";
        array_spinner[2] = "과장";
        array_spinner[3] = "대리";
        array_spinner[4] = "사원";
        array_spinner[5] = "신입사원";
        
        ArrayAdapter spinnerAdapter = new ArrayAdapter(this,
                android.R.layout.simple_spinner_item, array_spinner);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        spinner.setAdapter(spinnerAdapter);
        
        listQuery("", null);
        
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
                
//                Toast.makeText(MultiSendingSMS.this, "selected title : " +
//                        parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show(); 
                
                positionSelected = position;
                
                titleSelected = parent.getItemAtPosition(position).toString();
                if(titleSelected.equals("(모두)")){
                    titleSelected = "";
                }
                String searchtextString = searchtext.getText().toString();
                listQuery(titleSelected, searchtextString );
                
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        
        
        searchbtn.setOnClickListener(new OnClickListener() { 
            @Override
            public void onClick(View v) {
                String searchtextString = searchtext.getText().toString();
                String selectedpositionString = array_spinner[positionSelected];
                if(selectedpositionString.equals("(모두)")){
                    selectedpositionString = "";
                }
                listQuery(selectedpositionString, searchtextString);
                
                
            }
        });
        
        searchtext.addTextChangedListener(new TextWatcher() {
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String searchtextString = searchtext.getText().toString();
                String selectedpositionString = array_spinner[positionSelected];
                if(selectedpositionString.equals("(모두)")){
                    selectedpositionString = "";
                }
                listQuery(selectedpositionString, searchtextString);
                
            }
            
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        
        
    }
    
    public ArrayList<String> listQuery(String title, String name){
        
        
        if(name==null){
            name="";
        }
        
        Cursor cursor = getContentResolver().query(ProfileProvider.PROFILES_CONTENT_URI, null, Constants.TITLE+" LIKE "+"\"%"+title+"%\"" +" AND "+ Constants.NAME+" LIKE "+"\"%"+name+"%\"", null, Constants.TITLE_CODE+" , "+Constants._ID);
        ArrayList<String> teamArray = new ArrayList<String>();
        if(cursor.moveToFirst()){
            do{
                int sequence = 0;
                teamArray.add(cursor.getString(cursor.getColumnIndex("name"))+"  "+cursor.getString(cursor.getColumnIndex("title")));
                map.put(""+sequence, (String)cursor.getString(cursor.getColumnIndex("tel")));
                sequence++;
            }while(cursor.moveToNext());
        }
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, teamArray);
        
        teammultilist.setAdapter(adapter);
        teammultilist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
        return teamArray;
        
    }
    
    
    class MultiSMSadapter extends CursorAdapter {

        private Context mContext;
        private LayoutInflater mInflater;
        private BitmapFactory.Options options = new BitmapFactory.Options();

        public MultiSMSadapter(Context context) {
            super(context, null, true);
            this.mContext = context;
            mInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            options.inSampleSize = 4;
        }
        
        public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            if(!getCursor().moveToPosition(position))
                throw new IllegalStateException((new StringBuilder()).append("couldn't move cursor to position ").append(position).toString());
            
            if (convertView == null || convertView.getTag() == null) {
                v = newView(mContext, getCursor(), parent);
            } else {
                v = convertView;
            }
            bindView(v, mContext, getCursor());
            //Index header 추가(직급)
            bindSectionHeader(v, position, getCursor().getInt(getCursor().getColumnIndex(Constants.TITLE_CODE)));
            return v;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            
            //get information from cursor
            int idNum = cursor.getInt(cursor.getColumnIndex(Constants.ID_NUM));
            String name = cursor.getString(cursor.getColumnIndex(Constants.NAME));
            String title = cursor.getString(cursor.getColumnIndex(Constants.TITLE));
            String tel = cursor.getString(cursor.getColumnIndex(Constants.TEL));
            String email = cursor.getString(cursor.getColumnIndex(Constants.EMAIL));
            String location = cursor.getString(cursor.getColumnIndex(Constants.LOCATION));
            String job = cursor.getString(cursor.getColumnIndex(Constants.JOB));
            String manager = cursor.getString(cursor.getColumnIndex(Constants.MANAGER));

            //Store information in ViewHolder
            MultiSMSHolder holder = (MultiSMSHolder) view.getTag();
            if (holder == null) 
            {
                holder = new MultiSMSHolder();
                view.setTag(holder);
            }

            holder.idNum = idNum;
            holder.name = name;
            holder.title = title;
            holder.tel = tel;
            holder.email = email;
            holder.location = location;
            holder.job = job;
            holder.manager = manager;

            Bitmap bm = Util.getProfileImage(context, cursor, options);

            //Setting image
            QuickContactBadge imgProfile = (QuickContactBadge) view.findViewById(R.id.imgProfile);
            imgProfile.setImageBitmap(bm);
            imgProfile.setTag(tel);

            //Setting name + title 
            TextView nameProfile = (TextView) view.findViewById(R.id.nameProfile);
            nameProfile.setText(new StringBuffer(name).append(" ").append(title));
            
            //Setting Manager
            TextView managerProfile = (TextView) view.findViewById(R.id.manager);
            if(manager != null) {
                managerProfile.setVisibility(View.VISIBLE);
                managerProfile.setText(manager);
            } else {
                managerProfile.setVisibility(View.GONE);
            }
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = mInflater.inflate(R.layout.profile_list_item, parent, false);
            QuickContactBadge imgProfile = (QuickContactBadge) v.findViewById(R.id.imgProfile);
            //imgProfile.setOnClickListener(ProfileListActivity.this);
            return v;
        }
        
        private void bindSectionHeader(View itemView, int position, int title_code) {
        
            LinearLayout headerLayout = (LinearLayout)itemView.findViewById(R.id.listHeader);
            
//            if (mIndexer.contains(position)) {
//                headerLayout.setVisibility(View.VISIBLE);
//                
//                TextView textHeader = (TextView)itemView.findViewById(R.id.textHeader);
//                textHeader.setText(TITLE_MAP[title_code]);
//            } else {
//                headerLayout.setVisibility(View.GONE);
//            }
        }
    } 
    class MultiSMSHolder{
        public int idNum;
        public String name;
        public String title;
        public String tel;
        public String email;
        public String location;
        public String job;
        public String manager;
    }
}
